package com.bytetool.agent.method;

import com.bytetool.common.entity.PerformanceInfo;

import java.util.Optional;
import java.util.Stack;
import java.util.UUID;

/**
 * @author zouhuixing
 * @date 2024/3/31
 */
public class TraceInfoUtil {

    private static ThreadLocal<Stack<PerformanceInfo>> PERFORMANCE_INFO = new ThreadLocal<>();


    public static void initCurrentPerformanceInfo(String methodName) {
        Stack<PerformanceInfo> methodStack = PERFORMANCE_INFO.get();
        PerformanceInfo performanceInfo = new PerformanceInfo();
        performanceInfo.setStartTime(System.currentTimeMillis());
        performanceInfo.setMethodName(methodName);
        if (Optional.ofNullable(methodStack).isPresent() && methodStack.size() > 0) {
            performanceInfo.setParentMethodName(methodStack.peek().getMethodName());
            performanceInfo.setTraceId(methodStack.peek().getTraceId());
            methodStack.push(performanceInfo);

        } else {
            performanceInfo.setParentMethodName("");
            performanceInfo.setMethodName(methodName);
            performanceInfo.setTraceId(UUID.randomUUID().toString());
            methodStack = new Stack<>();
            methodStack.push(performanceInfo);
            PERFORMANCE_INFO.set(methodStack);
        }
    }

    public static PerformanceInfo getPerformanceInfo() {
        Stack<PerformanceInfo> methodStack = PERFORMANCE_INFO.get();
        PerformanceInfo pop = methodStack.pop();
        return pop;
    }
}
